import 'dart:convert';

import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/button/fixed_bottom_double_btn.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/custom_list_title.dart';
import 'package:boss/ui/widget/form/base_text_form_field.dart';
import 'package:boss/ui/widget/form/select_form_field.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:hi_common/hi_common.dart';
import 'package:router/annotation.dart';

import 'gradeDiscount.dart';

@RouterConfig(MemberAdd.pageName)
class MemberAdd extends StatefulWidget {
  static const pageName = '/memberAddPage';

  @override
  MymemberAdd createState() => MymemberAdd('添加会员');
}

class MymemberAdd extends BaseState<MemberAdd> {
  //卡种类id
  int cardCategorryId;

  //卡类型  0实体卡和1虚拟卡 两种
  int cardType = 1;

  //手机号
  int phoneNum;

  //姓名
  String name = '';

  //性别 1男 2女
  int sex = 1;

  //生日
  String birthday = '';

  //身份证号
  String identityCard = '';

  //职业
  String profession = '';

  //地址
  String address = '';

  //电子邮箱
  String email = '';

  //当前会员信息集合
  dynamic memberInformationObject;

  MymemberAdd(String pageName) : super(pageName);

  //身份证
  static bool identityId(String str) {
    return RegUtil.identityId.hasMatch(str);
  }

  //邮箱
  static bool emailReg(String str) {
    return RegUtil.emialReg.hasMatch(str);
  }

  @override
  void initState() {
    super.initState();

    queryMemberListDefault();
  }

  //新增会员
  addMemberFun({bool empty}) async {
    if (phoneNum == null) {
      toast("必填项填写不完整");

      return null;
    } else {
      if (!RegUtil.testPhone(phoneNum.toString())) {
        toast("手机账号格式有误");

        return null;
      }
    }

    if (identityCard != null) {
      if (identityCard != '') {
        if (identityId(identityCard.toString()) == false) {
          toast("身份证号格式有误");

          return null;
        }
      }
    }

    if (email != null) {
      if (email != '') {
        if (emailReg(email.toString()) == false) {
          toast("电子邮箱格式有误");

          return null;
        }
      }
    }

    if (cardCategorryId == null) {
      toast("请选择会员等级");
      return null;
    }

    try {
      showLoadingToast();

      var res = await api.addMember({
        'cardCategorryId': cardCategorryId,
        'cardType': cardType,
        'phoneNum': phoneNum,
        'name': name,
        'sex': sex,
        'birthday': birthday,
        'identityCard': identityCard,
        'profession': profession,
        'address': address,
        'email': email,
      });

      if (res.successful()) {
        toast("添加成功");
        if (empty == null) {
          Navigator.pop(context, true);
        } else {
//应当清空
//        phoneNum=null;
//        name='';
//        sex=1;
//        birthday='';
//        identityCard='';
//        profession='';
//        address='';
//        email='';
//        setState(() {});
//        print("______233");

        }
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //查询所有会员等级list中设置默认的
  queryMemberListDefault() async {
    try {
      Future.delayed(Duration(milliseconds: 0)).then((e) {
        showLoadingToast();
      });

      var res = await api.queryStoreMemberRank();

      if (res.successful()) {
        var dataArr = res.data ?? [];

        if (dataArr.length != 0) {
          var current = dataArr.firstWhere(
            (item) => item["isDefaultRank"] == 1,
            orElse: () => null,
          );

          memberInformationObject = current;

          if (memberInformationObject == null) {
            cardCategorryId = null;
          } else {
            cardCategorryId = memberInformationObject["id"];
          }

          setState(() {});
        }
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //卡片折数
  cardRate(str) {
    if (str == null) {
      return '';
    } else {
      if (str["discountCategory"] == 0) {
        return '';
      }
      if (memberInformationObject["extra"] == null) {
        return '';
      } else {
        return ((json.decode(memberInformationObject["extra"])["discountRate"]) / 10).toString() + '折';
      }
    }
  }

  //卡片钱数
  cardMoneyNum(str) {
    if (str == null) {
      return '';
    } else {
      if (memberInformationObject["extra"] == null) {
        return '';
      } else {
        return ((memberInformationObject["targetAmount"] / 100)).toString() + '元 ';
      }
    }
  }

  //iamge 图文
  imageTitle() {
    return Container(
      child: Stack(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(
              30.w,
            ),
            child: BaseImage(
              '${"assets/image/memberAdministration1.png"}',
              width: double.infinity,
            ),
          ),
          Positioned(
            top: 50.w,
            left: 0,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(
                    left: 82.w,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        "${memberInformationObject == null ? '- -' : (memberInformationObject["rankName"] == '' ? '- -' : memberInformationObject["rankName"])}",
                        style: TextStyleConstant().white_46,
                      ),
                      SizedBox(
                        height: 22.w,
                      ),
                      Text(
                        "${memberInformationObject == null ? '- -' : (memberInformationObject["discountCategory"] == 0 ? '无优惠' : (memberInformationObject["discountCategory"] == 1 ? '整单折扣' : '菜品会员价'))} ${memberInformationObject == null ? '' : memberInformationObject["discountCategory"] == 1 ? cardRate(memberInformationObject) : ''}",
                        //整单优惠9.8折

                        style: TextStyleConstant().white_28,
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 54.w,
                ),
                Container(
                  margin: EdgeInsets.only(
                    left: 82.w,
                  ),
                  decoration: BoxDecoration(
                    border: memberInformationObject != null
                        ? Border.all(
                            color: Colors.white,
                            width: 1,
                          )
                        : null,
                    borderRadius: BorderRadius.circular(
                      24.w,
                    ),
                  ),
                  height: 48.w,
                  child: Center(
                    child: Text(
                      "   ${memberInformationObject == null ? '' : (memberInformationObject["upgradeConditionType"] == 1 ? '无升级规' : (memberInformationObject["upgradeConditionType"] == 2 ? '充值' : (memberInformationObject["upgradeConditionType"] == 3 ? '消费' : '充值或消费')))}  ${memberInformationObject == null ? '' : memberInformationObject["upgradeConditionType"] == 1 ? '' : cardMoneyNum(memberInformationObject)} ",
                      style: TextStyleConstant().white_26,
                    ),
                  ),
                )
              ],
            ),
          ),
          Positioned(
            right: 0,
            bottom: 62.w,
            child: Padding(
              padding: EdgeInsets.only(
                right: 60.w,
              ),
              child: InkWell(
                onTap: () async {
                  var res = await Navigator.pushNamed(context, GradeDiscount.pageName, arguments: {"needBack": true});
                  if (res != null) {
                    memberInformationObject = res;
                    cardCategorryId = memberInformationObject["id"];

                    setState(() {});
                  }
                },
                child: Container(
                  child: Text(
                    "调整等级 >",
                    style: TextStyleConstant().white_22,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  HeaderTitle(String title) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(
          height: 20.w,
        ),
        Row(
          children: <Widget>[
            Container(
              width: 6.w,
              height: 30.w,
              decoration: BoxDecoration(
                color: Color.fromRGBO(87, 112, 246, 1),
                borderRadius: BorderRadius.circular(
                  3.w,
                ),
              ),
            ),
            Text(
              "$title",
              style: TextStyleConstant().appBarTitle,
            ),
          ],
        ),
        SizedBox(
          height: 20.w,
        ),
      ],
    );
  }

  contentList() {
    return Container(
      padding: EdgeInsets.only(
        left: 30.w,
        right: 30.w,
      ),
      width: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          HeaderTitle("  会员信息"),

          BaseTextFormField(
            inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
            keyboardType: TextInputType.number,
            prefixText: '手机号',
            maxLength: 12,
            isRequired: true,
            hintText: '请输入手机号',
            initialValue: (phoneNum ?? '').toString(),
            onChanged: (value) {
              phoneNum = num.parse(value);
              setState(() {});
            },
          ),
          BaseTextFormField(
            prefixText: '姓名',
            isRequired: false,
            hintText: '请输入姓名',
            maxLength: 10,
            initialValue: name ?? '',
            onChanged: (value) {
              name = value;
              setState(() {});
            },
          ),
          Container(
            child: SelectFormField<String>(
              title: '性别',
              hintText: '请选择',
              items: [
                {"name": "男", "key": 1},
                {"name": "女", "key": 2},
              ].map((item) => SelectItem(value: item["key"].toString(), title: item["name"])).toList(),
              value: sex.toString(),
              onChanged: (value) {
                sex = int.parse((value));
                setState(() {});
              },
            ),
          ),

          //生日
          Container(
            child: CustomListTitle(
              title: Row(
                children: <Widget>[
                  Text(
                    "生日",
                    style: TextStyleConstant().normal_1_28,
                  ),
                ],
              ),
              trailing: Row(
                children: <Widget>[
                  Text(
                    '${birthday == '' ? "请选择" : birthday}',
                    style: birthday == "" ? TextStyleConstant().normal_4_28 : TextStyleConstant().normal_1_28,
                  ),
                  Container(
                    margin: EdgeInsets.only(
                      left: 10.w,
                    ),
                    child: BaseImage(
                      'assets/image/arrow_right_icon.png',
                      width: 13.w,
                      height: 30.w,
                    ),
                  ),
                ],
              ),
              onTap: () {
                DatePicker.showDatePicker(
                  context,
//                  dateFormat:'YYYY MM dd',
//                minDateTime:DateTime.now(),
                  maxDateTime: DateTime.now(),
                  initialDateTime: DateTime.now(),
                  locale: DateTimePickerLocale.zh_cn,
                  pickerMode: DateTimePickerMode.date,
                  onConfirm: (dateTime, _) {
                    birthday = dateTime.toString().substring(0, 10);
                    setState(() {});
                  },
                );
              },
            ),
          ),

          BaseTextFormField(
            prefixText: '身份证号',
            isRequired: false,
            hintText: '请输入身份证号码',
            initialValue: identityCard ?? '',
            onChanged: (value) {
              identityCard = value;
              setState(() {});
            },
          ),

          BaseTextFormField(
            prefixText: '职业',
            isRequired: false,
            hintText: '请输入职业',
            initialValue: profession ?? '',
            onChanged: (value) {
              profession = value;
              setState(() {});
            },
          ),
          BaseTextFormField(
            prefixText: '地址',
            isRequired: false,
            hintText: '请输入您的地址',
            initialValue: address ?? '',
            onChanged: (value) {
              address = value;
              setState(() {});
            },
          ),
          BaseTextFormField(
            prefixText: '电子邮箱',
            isRequired: false,
            hintText: '请输入您的邮箱地址',
            initialValue: email ?? '',
            onChanged: (value) {
              email = value;
              setState(() {});
            },
          ),
        ],
      ),
    );
  }

  bodyPage() {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          imageTitle(),
          contentList(),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CenterTitleAppBar(
        title: '会员新增',
        actions: <Widget>[],
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              child: bodyPage(),
            ),
            FixedBottomDoubleBtn(
              second: '保存并新增',
              onFirst: () async {
                addMemberFun();
//                Navigator.pop(context);
              },
              onSecond: () async {
                addMemberFun(empty: true);
              },
              isShowShadow: false,
            )
          ],
        ),
      ),
    );
  }
}
